import { useState } from "react";
import { Menu } from "antd";
import items from "@/config/nav";
import { useLocation } from "react-router-dom";
import { Link } from "react-router-dom";

/* 设计下面的导航___小雨的工程化设计 */
let firstLevelKey = 0;
let navBarItmes = items.map((item) => {
  firstLevelKey += 1;
  const topItem = {
    key: firstLevelKey,
    icon: item.icon,
    label: item.label.title,
    children: [],
  };
  let secondLevelKey = 0;
  topItem.children = item.children.map((child) => {
    secondLevelKey = secondLevelKey + 1;
    return {
      /* 这个key也需要计算 */
      key: `${firstLevelKey}-${secondLevelKey}`,
      label: (
        <Link
          to={`/${item.label.path}/${child.label.path}`}
          state={{ title: child.label.title }}
        >
          {child.label.title}
        </Link>
      ),
    };
  });
  return topItem;
});

const getLevelKeys = (items1) => {
  const key = {};
  const func = (items2, level = 1) => {
    items2.forEach((item) => {
      if (item.key) {
        key[item.key] = level;
      }
      if (item.children) {
        func(item.children, level + 1);
      }
    });
  };
  func(items1);
  return key;
};
const levelKeys = getLevelKeys(navBarItmes);
const App = () => {
  // 可以在这里做进一步逻辑问题，根据URL来进行判断
  const location = useLocation();
  const lastPath = location.pathname.split("/").pop();
  const frontFix = lastPath.split("-")[0];

  const [stateOpenKeys, setStateOpenKeys] = useState([frontFix, lastPath]); // 显示展开点
  const onOpenChange = (openKeys) => {
    const currentOpenKey = openKeys.find(
      (key) => stateOpenKeys.indexOf(key) === -1
    );
    // open
    if (currentOpenKey !== undefined) {
      const repeatIndex = openKeys
        .filter((key) => key !== currentOpenKey)
        .findIndex((key) => levelKeys[key] === levelKeys[currentOpenKey]);
      setStateOpenKeys(
        openKeys
          // remove repeat key
          .filter((_, index) => index !== repeatIndex)
          // remove current level all child
          .filter((key) => levelKeys[key] <= levelKeys[currentOpenKey])
      );
    } else {
      // close
      setStateOpenKeys(openKeys);
    }
  };
  return (
    <Menu
      mode="inline"
      defaultSelectedKeys={[lastPath]} /* 显示高亮的地方 */
      openKeys={stateOpenKeys}
      onOpenChange={onOpenChange}
      items={navBarItmes}
    />
  );
};
export default App;
